package com.andy.common.base

import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.andy.common.exception.TokenInvalidException
import com.andy.logcat.LogUtils
import kotlinx.coroutines.TimeoutCancellationException

/**
 * Author:Andy
 * Date:2023/3/20 16:57
 * Description:BaseVMActivity
 */
abstract class BaseVMActivity<VB : ViewBinding, VM : BaseViewModel> : BaseActivity<VB>() {
    protected open lateinit var mViewModel: VM
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initVM()
        observer()
        initObserve()
        initData()
        initAction()

    }

    private fun initVM() {
        mViewModel = ViewModelProvider(this)[viewModelClass()]
    }

    private fun observer() {
        mViewModel.run {
            getError().observe(this@BaseVMActivity) {
                requestError(it)
            }
            getFinally().observe(this@BaseVMActivity) {
                requestFinally(it)
            }
        }
    }

    /**
     * 用于初始化视图
     */
    abstract fun initObserve()

    /**
     * 用于初始化数据
     */
    abstract fun initData()

    /**
     * 用于初始化点击事件
     */
    abstract fun initAction()

    open fun requestError(it: Exception) {
        it.run {
            when (it) {
                is TimeoutCancellationException -> {
                    LogUtils.e("请求超时")
                }

                is TokenInvalidException -> {
                    LogUtils.e("登录超时")
                }

                else -> {
                    LogUtils.e("其他错误")
                }
            }
        }
    }

    open fun requestFinally(it: Int) {

    }

    abstract fun viewModelClass(): Class<VM>

    override fun onDestroy() {
        super.onDestroy()
        mViewModel.release()
    }
}